<?php

namespace App\Containers\AppSection\Authentication\Claims;

use App\Containers\AppSection\Profile\Tasks\FindLatestProfileByUserIdTask;
use App\Containers\AppSection\Profile\Tasks\FindProfileByIdTask;
use App\Ship\Exceptions\AuthenticationException;

class ProfileClaim
{
    public function handle($token, $next)
    {
        $profileId = request()->input('profile_id');

        if (!empty($profileId)) {
            $profile = app(FindProfileByIdTask::class)->run($profileId);
        }

        if (!empty($profile) && $profile->user->id !== $token->getUserIdentifier()) {
            throw new AuthenticationException(__('ship::auth.profile'));
        }
        if (empty($profile) || $profile->user->id !== $token->getUserIdentifier())
            $profile = app(FindLatestProfileByUserIdTask::class)->run($token->getUserIdentifier());

        $token->addClaim('profileId', $profile->id);

        return $next($token);
    }
}
